<?php
namespace App\Service\Admin;

use App\Service\BaseService as Service;
use Illuminate\Support\Facades\DB;

class BaseService extends Service
{
    //基础服务

    //通过token获取uid
    public function getUidByToken($token)
    {
        if (!$token) {
            return 0;
        }
        $res = (array) DB::table($this->dbUlog)->where('token', $token)->first();
        if (empty($res)) {
            return 0;
        }
        return $res['uid'];
    }

    //记录登录错误信息
    public function loginMsg($pas)
    {
        if (!isset($pas['uid']) || !$pas['uid']) {
            $pas['uid'] = 0;
        }
        if (!isset($pas['ip']) || $pas['ip']) {
            $pas['ip'] = $this->getUserIp();
        }
        return $this->dbInsertOne($this->dbUlog, $pas);
    }

    //获取用户手机端IP
    public function getUserIp()
    {
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            // 如果使用了代理，通过这种方式获取真实的IP地址
            $clientIP = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // 对于使用了CDN或者反向代理的请求，可能需要从HTTP头中获取真实的IP地址
            $clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            // 没有代理的情况下直接获取IP地址
            $clientIP = $_SERVER['REMOTE_ADDR'];
        }
        return $clientIP;
    }

//    /**
//     * 插入接口统计
//     * @param string $phone
//     */
//    public function addApiCount($token)
//    {
//        $uid = $this->getUidByToken($token);
//        $uri = $_SERVER['REQUEST_URI'];
//        $resOne = (array) DB::table($this->dbDoc)->where('uri', $uri)->first();
//        if (!empty($resOne)) {
//            DB::table($this->dbDoc)->where('id', $resOne['id'])
//                ->update(['count' => $resOne['count'] + 1]);
//            DB::table($this->dbDocCount)->insertGetId([
//                'uid' => $uid,
//                'doc_id' => $resOne['id'],
//                'addtime' => toDate(),
//            ]);
//        }
//        return $uid;
//    }

    //模板的接口请求日志
    public function tmpLogAdd($pas)
    {
        $api_id = 0;
        $url = isset($pas['s'])&&$pas['s'] ? $pas['s'] : '';
        if ($url) {
            $docOne = (array) $this->dbConn($this->dbTmpDoc)
                ->where('del', 0)
                ->where('url', $url)
                ->first();
            $api_id = empty($docOne) ? 0 : $docOne['id'];
        }
        return $this->dbConn($this->dbTmpDocLog)->insertGetId([
            'doc_id' => $api_id,
            'req_json' => json_encode($pas, JSON_UNESCAPED_UNICODE),
            'addtime' => toDate(),
        ]);
    }

    //模板的接口返回更新
    public function tmpLogModify($log_id, $pas)
    {
        return $this->dbConn($this->dbTmpDocLog)->where('id', $log_id)
            ->update([
                'back_json' => json_encode($pas, JSON_UNESCAPED_UNICODE),
                'uptime' => toDate(),
            ]);
    }
}